package cn.xz.hfsk.base

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import java.lang.ref.WeakReference
import java.util.*

class BaseApplication : Application() {

    companion object {
        var  mContext: Application? = null
        fun getContext(): Context{
            return mContext!!
        }

        //当前处于活动状态的Activity
        var mActivityReference: WeakReference<Activity>? = null
        fun getCurrentActivity(): Activity? {
            return mActivityReference?.get()
        }

        //存储当前存在的Activity
        var mActivityList: LinkedList<Activity>? = null
        fun getActivityList(): LinkedList<Activity>? {
            return mActivityList
        }

    }

    override fun onCreate() {
        super.onCreate()
        mContext = this
        sameInit()
    }

    private fun sameInit(){
        this.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks{
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                setCurrentActivity(activity)
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
                setCurrentActivity(activity)
                setActivityList(activity)
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                removeActivity(activity)
            }

        })
    }

    fun setCurrentActivity(activity: Activity?) {
        if (activity != null){
            mActivityReference = WeakReference(activity)
        }else{
            mActivityReference?.clear()
        }
    }

    fun setActivityList(activity: Activity?){
        if (mActivityList == null){
            mActivityList = LinkedList()
        }
        mActivityList!!.add(activity!!)
    }

    fun removeActivity(a: Activity){
        if (mActivityList != null){
            mActivityList!!.remove(a)
        }
    }
}

